import React, {Fragment, Component} from 'react';
import PropTypes from 'prop-types';
import {Modal, Collapse, Form, Row, Col, Button, Card} from 'antd';
import {warrantyPolicyType, vehicleProperty, vehicleClaimType} from '../../Enum';
import WrappedPopconfirm from '../../common/WrappedPopconfirm';
import {FORM_OPTIONS} from '../../constants';
import styles from '../style.css';
import WrappedSelect from '../../common/WrappedSelect';
import ProductCategoryPanel from './ProductCategoryPanel';
import VehicleSelectPanel from './VehicleSelectPanel';
import {injectIntl, formatMessage, language} from '../intl';
import ImportPanel from './ImportPanel';
import {conventEnumValueToString, uuid} from '../../utils';
import AddMaterial from './AddMaterial';
const FormItem = Form.Item;
const Panel = Collapse.Panel;
class AddVehicle extends Component {
    state = {
        loading: false,
        hasOperat: false,
        showCategory: false,
        showVehicle: false,
        confirmLoading: false,
        showImportPanel: false
    };

    showCategory = () => {
        this.setState(state => ({
            showCategory: !state.showCategory
        }));
    };

    showVehicle = () => {
        this.setState(state => ({
            showVehicle: !state.showVehicle
        }));
    };

    handleFilterChange = (value, name) => {
        this.props.onChange(value, `${this.props.name}.${name}`);
    };

    renderVehiclesPanel = () => {
        const {vehicles = [], warrantyPolicyType: type} = this.props.data;

        return vehicles.map((item, index) => {
            const header = (
                <Row>
                    <Col span={22} className={styles.edit}>
                        {
                            type === warrantyPolicyType.标准
                                ? <strong>{`${item.productCategoryCode} / ${conventEnumValueToString(vehicleProperty, item.vehicleProperty)}` }</strong>
                                : <strong>{item.vin}</strong>
                        }
                    </Col>
                    <Col span={2} className={`col-align-right ${styles.collapseBtn}`}>
                        {<a data-index={index} onClick={this.onClickDelete}>
                            {formatMessage({
                                id: 'addVehicle.material.deleteBtn',
                                defaultMessage: '删除'
                            })}
                        </a>}
                    </Col>
                </Row>
            );
            return (
                <Panel key={item.id} header={header}>
                    <Row className={styles.marginBottom}>
                        {
                            type === warrantyPolicyType.标准
                                ? (
                                    <Fragment>
                                        <Col {...FORM_OPTIONS.col}>
                                            <FormItem label={formatMessage({
                                                id: 'productCategoryCode',
                                                defaultMessage: '车型'
                                            })} {...FORM_OPTIONS.item}>
                                                <span>{item.productCategoryCode}</span>
                                            </FormItem>
                                        </Col>
                                        <Col {...FORM_OPTIONS.col}>
                                            <FormItem label={formatMessage({
                                                id: 'vehicleProperty',
                                                defaultMessage: '车辆属性'
                                            })} {...FORM_OPTIONS.item}
                                            validateStatus={this.props.isValidate &&
                                                !item.vehicleProperty ? 'error' : null}
                                            required>
                                                <WrappedSelect
                                                    name={`vehicles[${index}].vehicleProperty`}
                                                    value={item.vehicleProperty}
                                                    options={vehicleProperty.toList(language)}
                                                    onChange={this.handleFilterChange} />
                                            </FormItem>
                                        </Col>
                                        <Col {...FORM_OPTIONS.col}>
                                            <FormItem label={formatMessage({
                                                id: 'vehicleClaimType',
                                                defaultMessage: '索赔类别'
                                            })} {...FORM_OPTIONS.item}
                                            validateStatus={this.props.isValidate &&
                                                !item.vehicleClaimType ? 'error' : null}
                                            required>
                                                <WrappedSelect
                                                    name={`vehicles[${index}].vehicleClaimType`}
                                                    value={item.vehicleClaimType}
                                                    options={vehicleClaimType.toList(language)}
                                                    onChange={this.handleFilterChange} />
                                            </FormItem>
                                        </Col>
                                    </Fragment>
                                )
                                : (<Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'vin',
                                        defaultMessage: 'VIN'
                                    })} {...FORM_OPTIONS.item}>
                                        <span>{item.vin}</span>
                                    </FormItem>
                                </Col>)
                        }
                    </Row>
                    <AddMaterial
                        name={`${this.props.name}.vehicles[${index}]`}
                        onSelect={this.props.onSelect}
                        onChange={this.props.onChange}
                        onRemove={this.props.onRemove}
                        onRemoveAll={this.props.onRemoveAll}
                        isValidate={this.props.isValidate}
                        data={item.materials || []}
                        dealerId={this.props.dealerId}/>
                </Panel>
            );
        });
    }
    onClickDelete = e => {
        const index = e.currentTarget.dataset.index;
        this.props.onRemove(`${this.props.name}.vehicles`, index);
    }

    onDeleteAll = () => {
        this.props.onRemoveAll(`${this.props.name}.vehicles`);
    }

    onSelectCategoryOrVehicle = records => {
        if(records.length)
            this.props.onSelect(`${this.props.name}.vehicles`, records, `${this.props.name}`);
        
        this.setState({
            showCategory: false,
            showVehicle: false
        });
    }

    onClickAddCategory = e => {
        e.stopPropagation();
        this.setState({
            showCategory: true
        });
    };

    onClickAddVehicle = e => {
        e.stopPropagation();
        this.setState({
            showVehicle: true
        });
    };
    onClickImportBtn = e => {
        e.stopPropagation();
        this.setState({showImportPanel: true});
    }
    onCloseImportPanel = () => {
        this.setState({showImportPanel: false});
    }
    onImportChange = records => {
        if(records.payload.content.length)
            this.props.onSelect(`${this.props.name}.vehicles`, records.payload.content.map(item => ({
                id: uuid(),
                vin: item.vin,
                vehicleId: item.id,
            })));
        this.setState({showImportPanel: false});
    }

    render() {
        const {vehicles = [], warrantyPolicyType: type} = this.props.data;
        const currentSelectVinRowKeys = [];
        const currentSelectCategoryRowKeys = [];
        
        vehicles.forEach(item => {
            currentSelectVinRowKeys.push(item.vehicleId);
            currentSelectCategoryRowKeys.push(item.productCategoryId);
        });

        return (
            <React.Fragment>
                <Modal
                    title={formatMessage({
                        id: 'addVehicle.productCategory.modal.title',
                        defaultMessage: '车型信息'
                    })}
                    width="60%"
                    maskClosable={false}
                    footer={null}
                    wrapClassName={styles.dataSelectModal}
                    destroyOnClose={true}
                    visible={this.state.showCategory}
                    onCancel={this.showCategory}>
                    <ProductCategoryPanel onSelect={this.onSelectCategoryOrVehicle}
                        currentSelectRowKeys={currentSelectCategoryRowKeys} />
                </Modal>
                <Modal
                    title={formatMessage({
                        id: 'addVehicle.vehicle.modal.title',
                        defaultMessage: '车辆信息'
                    })}
                    width="80%"
                    maskClosable={false}
                    footer={null}
                    wrapClassName={styles.dataSelectModal}
                    destroyOnClose={true}
                    visible={this.state.showVehicle}
                    onCancel={this.showVehicle}>
                    <VehicleSelectPanel onSelect={this.onSelectCategoryOrVehicle}
                        currentSelectRowKeys={currentSelectVinRowKeys} />
                </Modal>
                {
                    this.state.showImportPanel &&
                    <ImportPanel
                        selectKey={'1'}
                        onCancel={this.onCloseImportPanel}
                        onImportChange={this.onImportChange} />
                }
                <Card
                    extra={<Fragment>
                        {
                            type === warrantyPolicyType.标准 ? <div>
                                <Button size="small" onClick={this.onClickAddCategory}>{formatMessage({
                                    id: 'addVehicle.detail.btn.add',
                                    defaultMessage: '新增'
                                })}</Button>
                                {
                                    vehicles.length ? (<WrappedPopconfirm
                                        id="deleteAll"
                                        placement="topLeft"
                                        key="deleteAll"
                                        onConfirm={this.onDeleteAll}
                                        title={formatMessage({
                                            id: 'addVehicle.popconfirm.delete.message',
                                            defaultMessage: '是否确认清空?'
                                        })}
                                        okText={formatMessage({
                                            id: 'addVehicle.popconfirm.confirm',
                                            defaultMessage: '确认'
                                        })}
                                        cancelText={formatMessage({
                                            id: 'addVehicle.popconfirm.cancel',
                                            defaultMessage: '取消'
                                        })}>
                                        <Button size="small">{formatMessage({
                                            id: 'addVehicle.deleteAll',
                                            defaultMessage: '清空'
                                        })}</Button>
                                    </WrappedPopconfirm>)
                                        : (<Button size="small">{formatMessage({
                                            id: 'addVehicle.deleteAll',
                                            defaultMessage: '清空'
                                        })}</Button>)
                                }
                            </div>
                                : <div>
                                    <Button
                                        size="small"
                                        onClick={this.onClickImportBtn}>
                                        {formatMessage({
                                            id: 'newPanel.operation.import',
                                            defaultMessage: '导入'
                                        })}
                                    </Button>
                                    <Button size="small" onClick={this.onClickAddVehicle}>{formatMessage({
                                        id: 'addVehicle.btn.add',
                                        defaultMessage: '新增'
                                    })}</Button>
                                    {
                                        vehicles.length ? (<WrappedPopconfirm
                                            id="deleteAll"
                                            placement="topLeft"
                                            key="deleteAll"
                                            onConfirm={this.onDeleteAll}
                                            title={formatMessage({
                                                id: 'addVehicle.popconfirm.delete.message',
                                                defaultMessage: '是否确认清空?'
                                            })}
                                            okText={formatMessage({
                                                id: 'addVehicle.popconfirm.confirm',
                                                defaultMessage: '确认'
                                            })}
                                            cancelText={formatMessage({
                                                id: 'addVehicle.popconfirm.cancel',
                                                defaultMessage: '取消'
                                            })}>
                                            <Button size="small">{formatMessage({
                                                id: 'addVehicle.deleteAll',
                                                defaultMessage: '清空'
                                            })}</Button>
                                        </WrappedPopconfirm>)
                                            : (<Button size="small">{formatMessage({
                                                id: 'addVehicle.deleteAll',
                                                defaultMessage: '清空'
                                            })}</Button>)
                                    }
                                </div>
                        }
                        
                    </Fragment>}
                    title={formatMessage({
                        id: 'addVehicle.vehicles.title',
                        defaultMessage: '车型车辆清单'
                    })}>
                    {
                        vehicles.length > 0 &&
                        <Collapse accordion>
                            {this.renderVehiclesPanel()}
                        </Collapse>
                    }
                </Card>
            </React.Fragment>
        );
    }
}
AddVehicle.propTypes = {
    dealerId: PropTypes.string,
};

export default injectIntl(AddVehicle);
